package day18;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。
 *
 *
 *
 * 示例 1：
 *
 *
 * 输入：root = [3,9,20,null,null,15,7]
 * 输出：[[3],[20,9],[15,7]]
 * 示例 2：
 *
 * 输入：root = [1]
 * 输出：[[1]]
 * 示例 3：
 *
 * 输入：root = []
 * 输出：[]
 */
class TreeNode {
      int val;
     TreeNode left;
     TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
public class Solution1 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root==null){
            return new ArrayList<>();
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        List<List<Integer>> list = new ArrayList<>();
        stack1.push(root);
        while (!stack1.empty()||!stack2.empty()){
            List<Integer> list1 = new ArrayList<>();
            while (!stack1.empty()) {
                TreeNode pop = stack1.pop();
                list1.add(pop.val);
                if(pop.left!=null) {
                    stack2.push(pop.left);
                }
                if(pop.right!=null){
                    stack2.push(pop.right);
                }

            }
            if(list1.size()>0){
                list.add(list1);
            }
            List<Integer> list2 =new ArrayList<>();
            while (!stack2.empty()){
                TreeNode pop = stack2.pop();
                list2.add(pop.val);
                if(pop.right!=null){
                    stack1.push(pop.right);
                }
                if(pop.left!=null){
                    stack1.push(pop.left);
                }

            }
            if(list2.size()>0){
                list.add(list2);
            }
        }
        return  list;
    }
}
